package com.wandian.weather.mvvm.mapsearch;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.weather.R;
import com.wandian.weather.adapter.MapSearchRecycleAdapter;
import com.wandian.weather.databinding.MapActivitySearchBinding;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.mylib.libcore.config.AppSPKeyConfig.CITY_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.CITY_STREET_NAME;


/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 地图搜索
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_MAP_SEARCH)
public class MapSearchActivity extends BaseMVVMActivity<MapSearchViewModel> implements  PoiSearch.OnPoiSearchListener {
    private MapActivitySearchBinding dataBinding;
    private MapSearchRecycleAdapter mapSearchRecycleAdapter;
    private MapView mMapView;
    private AMap mAMap;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private float zoomToNumber = 12;
    //poiSearch相关
    private PoiSearch poiSearch;
    private PoiSearch.Query query;
    boolean isPoiSearched = false; //是否进行poi搜索
    private Map<String, String> currentInfo = new HashMap<>();
    private double mCurrentLat;
    private double mCurrentLng;
    private PoiItem choosePoiItem;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.map_activity_search);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initDataView();
        initClink();
        //初始化map资源
        initMap(savedInstanceState);
        //初始化recycle
        initRecycle();
    }

    private void initDataView(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);

        //切换
        dataBinding.tvAddressChange.setOnClickListener(v -> {
            if(!UIUtils.isEmpty(choosePoiItem)){
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_NAME,choosePoiItem.getCityName()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_STREET_NAME,choosePoiItem.getTitle()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue("select_lat",choosePoiItem.getLatLonPoint().getLatitude()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue("select_log",choosePoiItem.getLatLonPoint().getLongitude()+"");
                EventBus.getDefault().post(new ChangeMessage("changeWeatherLocal"));
                finish();
            }
        });
    }

    private void initRecycle(){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        dataBinding.recycleView.setLayoutManager(layoutManager);
        mapSearchRecycleAdapter = new MapSearchRecycleAdapter(R.layout.map_item_location_item);
        dataBinding.recycleView.setAdapter(mapSearchRecycleAdapter);
        mapSearchRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //关闭软件盘
                finishhideSoftBoard();
                PoiItem item =(PoiItem) adapter.getData().get(position);
                choosePoiItem = (PoiItem)adapter.getData().get(position);
                if(!UIUtils.isEmpty(choosePoiItem)){
                    //在地图上添加一个marker，并将地图中移动至此处
                    MarkerOptions mk = new MarkerOptions();
                    mk.icon(BitmapDescriptorFactory.defaultMarker());
                    mk.title(item.getAdName());
                    LatLng ll = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
                    mk.position(ll);
                    //清除所有marker等，保留自身
                    mAMap.clear(true);
                    CameraUpdate cu = CameraUpdateFactory.newLatLng(ll);
                    mAMap.animateCamera(cu);
                    mAMap.addMarker(mk);
                    mapSearchRecycleAdapter.notifySelectItemView(position);
                }
            }
        });
    }

    private void initClink(){

        dataBinding.toolBarIvBack.setOnClickListener(v ->   finish());

        dataBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //输入完成搜索周边
                if(!UIUtils.isEmpty(s) && !UIUtils.isEmpty(s.toString())){
                    searchPoi(s.toString(), 0, currentInfo.get("cityCode"), false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 搜索poi
     * @param key      关键字
     * @param pageNum  页码
     * @param cityCode 城市代码，或者城市名称
     * @param nearby   是否搜索周边
     */
    void searchPoi(String key, int pageNum, String cityCode, boolean nearby) {
        isPoiSearched = true;
        query = new PoiSearch.Query(key, "", cityCode);
        //keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，
        //POI搜索类型共分为以下20种：汽车服务|汽车销售|
        //汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
        //住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
        //金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(30);// 设置每页最多返回多少条poiitem
        query.setPageNum(pageNum);//设置查询页码
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        if (nearby) poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mCurrentLat, mCurrentLng), 1500));//设置周边搜索的中心点以及半径
        poiSearch.searchPOIAsyn();
    }

    private void initMap(Bundle savedInstanceState){
        mMapView = dataBinding.map;
        mMapView.onCreate(savedInstanceState);
        if (mAMap == null) {
            mAMap = mMapView.getMap();
        }

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.img_map_person));// 设置小蓝点的图标
        //myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(zoomToNumber)); //缩放比例
        mAMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        mAMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        mAMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        mAMap.setMaxZoomLevel(mAMap.getMaxZoomLevel());

        //地址监听事件
        mAMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                if (!isPoiSearched) {
                    //存储定位数据
                    mCurrentLat = location.getLatitude();
                    mCurrentLng = location.getLongitude();
                    String[] args = location.toString().split("#");
                    for (String arg : args) {
                        String[] data = arg.split("=");
                        if (data.length >= 2)
                            currentInfo.put(data[0], data[1]);
                    }
                    //搜索poi
                    searchPoi("", 0, currentInfo.get("cityCode"), true);
                    //latitude=41.652146#longitude=123.427205#province=辽宁省#city=沈阳市#district=浑南区#cityCode=024#adCode=210112#address=辽宁省沈阳市浑南区创新一路靠近东北大学浑南校区#country=中国#road=创新一路#poiName=东北大学浑南校区#street=创新一路#streetNum=193号#aoiName=东北大学浑南校区#poiid=#floor=#errorCode=0#errorInfo=success#locationDetail=24 #csid:1cce9508143d493182a8da7745eb07b3#locationType=5
                }
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        finishhideSoftBoard();
        // 销毁定位
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mMapView.onDestroy();
        super.onDestroy();
    }



    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        //填充数据，并更新
        if (poiResult != null) {
            ArrayList<PoiItem> result = poiResult.getPois();
            if (result.size() > 0) {
                //加载listview中数据
                mapSearchRecycleAdapter.setNewData(result);
                mapSearchRecycleAdapter.notifySelectItemView(-1);
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
